package com.ruoyi.common.utils.email;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.mail.ImageHtmlEmail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.MimeMessage;
import java.security.Security;
import java.util.Date;
import java.util.Properties;
import javax.mail.internet.InternetAddress;


public class EmailUtil {

    protected Logger log = LoggerFactory.getLogger(this.getClass());

    public final static String EMAIL_CENTER_CONFIG = "EMAILCenter";
    private String emailCenterConfig;//邮箱服务配置
    private static String hostname = "smtp.yandex.com";//邮箱服务名称
    private static String fromaddress = "verification@gcchub.io";//发送者邮箱地址
    private static String fromname = "verification@gcchub.io";//发送者邮箱名称
    private static String username = "verification@gcchub.io";//用户名
    private static String password = "Gcc.666";//密码

    /**
     * 接收人
     *
     * @param address 发送地址
     * @param name    邮件接收的用户名
     * @param subject 主题
     * @param content 内容
     * @return
     * @throws Exception
     */
    public static String sendEmail(String address, String name, String subject, String content) throws Exception {

        if (StringUtils.isEmpty(address)) {

            String result = "邮件接收地址为空!";
            //返回失败

            return result;
        }
        ImageHtmlEmail email = new ImageHtmlEmail();
        email.setHostName(hostname);
        email.setSSLOnConnect(true);
        email.addTo(address, name);
        email.setFrom(fromaddress, fromname);
        email.setAuthentication(username, password);
        email.setCharset("UTF-8");
        email.setSubject(subject);
        email.setHtmlMsg(content);
        email.setTextMsg("您的邮箱无法支持Html格式。");
        email.send();
//        log.info("[企业邮箱服务发送邮件|邮件发送成功|邮件接收地址：{}|接收人名字:{}|邮件标题:{}]", address, name, subject);
        return "SUCCESS";
    }


    @Autowired
    private JavaMailSender sender;


//    @Value("${mail.username}")
//    private String from;
//    @Value("${mail.password}")
//    private String psw;
//
//    @Value("${mail.host}")
//    private String host;


    /**
     * 使用加密的方式,利用465端口进行传输邮件,开启ssl
     *
     * @param to      为收件人邮箱
     * @param message 发送的消息
     */
    public String sendEmil(String to, String subject, String message) {
        try {
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            //设置邮件会话参数
            Properties props = new Properties();
            //邮箱的发送服务器地址
            props.setProperty("mail.smtp.host", hostname);
            props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            //邮箱发送服务器端口,这里设置为465端口
            props.setProperty("mail.smtp.port", "465");
            props.setProperty("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
//            final String username = from;
//            final String password = psw;
            //获取到邮箱会话,利用匿名内部类的方式,将发送者邮箱用户名和密码授权给jvm
            Session session = Session.getDefaultInstance(props, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
            //通过会话,得到一个邮件,用于发送
            Message msg = new MimeMessage(session);
            //设置发件人
            msg.setFrom(new InternetAddress(username));
            //设置收件人,to为收件人,cc为抄送,bcc为密送
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(to, false));
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(to, false));
            msg.setSubject(subject);
            //设置邮件消息
            msg.setText(message);
            //设置发送的日期
            msg.setSentDate(new Date());

            //调用Transport的send方法去发送邮件
            Transport.send(msg);
            return "SUCCESS";
        } catch (Exception e) {
            e.printStackTrace();
            return "FAIL";
        }

    }

    /**
     * @param from    账号
     * @param pass    密码
     * @param to      收件人邮箱
     * @param subject 主题
     * @param body    正文
     * @throws AddressException
     * @throws MessagingException
     */
    public static String sendFromYandex(String to, String subject, String body) {
        Properties props = System.getProperties();
        props.put("mail.smtp.host", hostname);
        props.put("mail.smtp.user", username);
        props.put("mail.smtp.password", password);
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.quitwait", "false");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.debug", "true");
        try {
            Session session = Session.getInstance(props);
            session.setDebug(true);
            MimeMessage message = new MimeMessage(session);
            message.setHeader("Content-Type", "text/plain; charset=UTF-8");
            message.setSubject(subject, "UTF-8");
            message.setText(body, "UTF-8");

            message.setFrom(new InternetAddress(username));
            InternetAddress toAddress = new InternetAddress(to);
            message.addRecipient(Message.RecipientType.TO, toAddress);
            //设置在发送给收信人之前给自己（发送方）抄送一份，不然会被当成垃圾邮件，报554错
            message.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(to));

            message.setSubject(subject);
            message.setText(body);
            Transport transport = session.getTransport("smtp");
            transport.connect(hostname, username, password);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            return "SUCCESS";
        } catch (Exception e) {
            e.printStackTrace();
            return "FAIL";
        }
    }
}
